//
//  ViewPointController.m
//  ViewPoint
//
//  Created by Demiao Lin on 10/18/08.
//  Copyright 2008 Tsinghua. All rights reserved.
//

#import "ViewPointController.h"
#import "BoardsViewController.h"
#import "ConfigViewController.h"

#import "PostViewController.h"
#import "ThreadViewController.h"

#import "NewSMTH.h"

#define INDICATOR_VIEW	999

@implementation ViewPointController

@synthesize boardsViewController;
@synthesize configViewController;
@synthesize postViewController;
@synthesize threadViewController;

@synthesize tableView;

@synthesize posts;

- (id) init
{
	if( (self=[super init]) != nil ){
		
		self.title = @"Top 10";
        
        //configViewController = [[ConfigViewController alloc] initWithTitle:@"Configuration"];
        //boardsViewController = [[BoardsViewController alloc] initWithTitle:@"Boards"];
        //postViewController = [[PostViewController alloc] init];
        
        ConfigViewController *oneConfigViewController = [[ConfigViewController alloc] initWithTitle:@"Configuration"];
		//oneConfigViewController.smth = 
		self.configViewController = oneConfigViewController;
		[oneConfigViewController release];
        
        BoardsViewController *oneBoardsViewController = [[BoardsViewController alloc] initWithTitle:@"Boards"];
		self.boardsViewController = oneBoardsViewController;
		[oneBoardsViewController release];
        
        PostViewController *onePostViewController = [[PostViewController alloc] init];
		self.postViewController = onePostViewController;
		[onePostViewController release];
        
        ThreadViewController *oneThreadViewController = [[ThreadViewController alloc] init];
		self.threadViewController = oneThreadViewController;
		[oneThreadViewController release];
	}
	return self;
}

- (void)loadView {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	CGRect rect = [[UIScreen mainScreen] applicationFrame];
	
	contentView = [[[UIView alloc] initWithFrame:rect] autorelease];
	contentView.backgroundColor = [UIColor whiteColor];
	contentView.autoresizesSubviews = YES;
	contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	

	self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
	
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] 
											  initWithTitle:@"Config" 
											  style:UIBarButtonItemStylePlain 
											  target:self 
											  action:@selector(toConfigView:)] autorelease];
	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] 
											   initWithTitle:@"Boards" 
											   style:UIBarButtonItemStylePlain 
											   target:self 
											   action:@selector(toBoardsView:)] autorelease];
	
	
	/*
	rect.origin.x = 0.0f;
    rect.origin.y = 44.0f;
	textView = [[[UITextView alloc] initWithFrame:rect] autorelease];
	[textView setText:@"Top 10:\n1.\n2.\n3.\n4.\n5.\n6.\n7.\n8.\n9.\n10.\n"];
	
	//NSString *textContent = [NewSMTH getContentFromURL:@"http://ipsmth.appspot.com/vp/boards/"];
	//NSLog(textContent);
	//[textView setText:textContent];
    
	textView.editable = NO;
	textView.textAlignment = UITextAlignmentCenter;
	textView.font = [UIFont fontWithName:@"American Typewriter" size:20];
	textView.backgroundColor = [UIColor lightGrayColor];
	
	[contentView addSubview:textView];
	*/
	
	rect.size.height=44.0f;
	UITableView *oneTableView = [[[UITableView alloc] initWithFrame:rect
                                                              style:UITableViewStylePlain] autorelease];
	
    UIView *tableHeaderView = [[[UIView alloc] initWithFrame:rect] autorelease];
    //UIView *tableFooterView = [[[UIView alloc] initWithFrame:rect] autorelease];
    //tableHeaderView.tag = kHeaderViewTag;
    //tableFooterView.tag = kFooterViewTag;
    oneTableView.tableHeaderView = tableHeaderView;
    //oneTableView.tableFooterView = tableFooterView;
    
    [oneTableView setEditing:NO animated:YES];
    [oneTableView setAutoresizingMask: (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth) ];
	[oneTableView setDelegate: self];
    [oneTableView setDataSource: self];
	self.tableView = oneTableView;
	[contentView addSubview:oneTableView];
	
	rect = [[UIScreen mainScreen] applicationFrame];
	UIActivityIndicatorView *activityIndicator = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)] autorelease];
	[activityIndicator setCenter:CGPointMake(rect.size.width/2, rect.size.height/2-20)];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
	activityIndicator.tag = INDICATOR_VIEW;
    [contentView addSubview:activityIndicator];
    [activityIndicator startAnimating];
    
	self.view = contentView;
    [self setViewsRotation];
	
	//[[self navigationController] pushViewController:self.configViewController animated:NO];
	//[[self navigationController] popToRootViewControllerAnimated:NO];
	
	[pool release];
}

- (void) toBoardsView: (id) sender
{
	//self.title = @"Boards";
	[[self navigationController] pushViewController:self.boardsViewController animated:YES];
}

- (void) toConfigView: (id) sender
{
	//self.title = @"Configuration";
	[[self navigationController] pushViewController:self.configViewController animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)onetableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier = @"Top10Cell";
    UITableViewCell *cell = [onetableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        //CGRect cellFrame = CGRectMake(0,0,300,60);
        //cell = [[[UITableViewCell alloc] initWithFrame:cellFrame reuseIdentifier:CellIdentifier] autorelease];
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		
        CGRect titleLabelRect = CGRectMake(5,0,300,30);
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:titleLabelRect];
        [titleLabel setAutoresizingMask: UIViewAutoresizingFlexibleWidth];
        titleLabel.textAlignment = UITextAlignmentLeft;
        titleLabel.font = [UIFont boldSystemFontOfSize:18];
        //titleLabel.textColor = [UIColor grayColor];
        titleLabel.tag = kTitleTag;
        [cell.contentView addSubview: titleLabel];
        [titleLabel release];
        
        
        CGRect authorLabelRect = CGRectMake(5,30,95,20);
        UILabel *authorLabel = [[UILabel alloc] initWithFrame:authorLabelRect];
        authorLabel.textAlignment = UITextAlignmentLeft;
        authorLabel.font = [UIFont boldSystemFontOfSize:14];
        authorLabel.textColor = [UIColor purpleColor];
        authorLabel.tag = kAuthorTag;
        [cell.contentView addSubview: authorLabel];
        [authorLabel release];
        
        CGRect dateLabelRect = CGRectMake(100,30,195,20);
        UILabel *dateLabel = [[UILabel alloc] initWithFrame:dateLabelRect];
        dateLabel.textAlignment = UITextAlignmentRight;
        dateLabel.font = [UIFont boldSystemFontOfSize:14];
        dateLabel.textColor = [UIColor orangeColor];
        dateLabel.tag = kDateTag;
        [cell.contentView addSubview: dateLabel];
        [dateLabel release];
        
    }
    
    UILabel *title_label = (UILabel*)[cell.contentView viewWithTag:kTitleTag];
    UILabel *author_label = (UILabel*)[cell.contentView viewWithTag:kAuthorTag];
    UILabel *date_label = (UILabel*)[cell.contentView viewWithTag:kDateTag];
    
    Post *post = [self.posts objectAtIndex:[indexPath row]];
    title_label.text = [post title];
    author_label.text = [post user];
    date_label.text = [post date];
	
    return cell;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    [self setViewsRotation];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	[self loadTableView];
}

-(void) loadTableViewData:(id)object{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	if(!self.posts || [self.posts count]<=0){
        NSMutableArray *array = [[[[NewSMTH alloc] init] autorelease] getTop10Posts];
        if(array){
            self.posts = array;
            [self.tableView reloadData];
            [self.tableView flashScrollIndicators];
        }
    }
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
	[activityIndicator stopAnimating];
	[pool release];
}

-(void) loadTableView{
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    [activityIndicator startAnimating];
    [self performSelectorInBackground:@selector(loadTableViewData:) withObject:nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.posts count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 51;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Post *post = [self.posts objectAtIndex:[indexPath row]];
	//NSLog([post title]);
    [postViewController setPostViewWithTitle:[post title] board:[[[Board alloc] initWithBoardName:[post bname] bid:[post bid]] autorelease] post_id:[post tid] post_type:@"no"];
    [[self navigationController] pushViewController:postViewController animated:YES];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    Post *post = [self.posts objectAtIndex:[indexPath row]];
    
    /*
    [postViewController setPostViewWithTitle:[post title] board:[[[Board alloc] initWithBoardName:[post bname] bid:[post bid]] autorelease] post_id:[post tid] post_type:@"no"];
    [[self navigationController] pushViewController:postViewController animated:YES];
    */
    
    [threadViewController setThreadViewWithTitle:[post title] board:[[[Board alloc] initWithBoardName:[post bname] bid:[post bid]] autorelease] thread_id:[post tid] post_id:[post tid]];
	[[self navigationController] pushViewController:self.threadViewController animated:YES];
}

- (void) setViewsRotation {
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    
    UIInterfaceOrientation orientation = self.interfaceOrientation;
    if(orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight){
        [tableView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 300.0f)];
        [tableView.tableHeaderView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 32.0f)];
        [activityIndicator setCenter:CGPointMake(240, 140)];
	}else{
		[tableView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
        [tableView.tableHeaderView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(160, 220)];
	}
	[self.view bringSubviewToFront:activityIndicator];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)dealloc {
    [boardsViewController release];
    [configViewController release];
    [postViewController release];
	[threadViewController release];
    [posts release];
	[tableView release];
	[contentView release];
    [super dealloc];
}


@end
